<template>
  <header class="header">
    <div class="container">
      <div class="header-top">
        <div class="logo">
          <router-link to="/">哔哩哔哩</router-link>
        </div>
        
        <!-- 搜索框 -->
        <div class="search-box">
          <input 
            type="text" 
            placeholder="搜索你想看的内容..."
            class="search-input"
          />
          <button class="search-btn">
            <i class="icon-search"></i>
          </button>
        </div>
        
        <!-- 用户区域 - 根据登录状态显示不同内容 -->
        <div class="user-area">
          <!-- 未登录状态 -->
          <div v-if="!isLoggedIn" class="login-area">
            <router-link to="/login" class="login-btn">登录</router-link>
          </div>
          
          <!-- 已登录状态 -->
          <div v-else class="user-info">
            <div class="user-dropdown">
              <button class="user-btn" @click="toggleDropdown">
                {{ currentUser?.username || '用户' }}
                <span class="dropdown-arrow">▼</span>
              </button>
              <div v-if="showDropdown" class="dropdown-menu">
                <!-- 个人中心 - 空链接 -->
                <a href="#" class="dropdown-item">个人中心</a>
                <!-- 注销按钮 -->
                <button @click="handleLogout" class="dropdown-item logout">注销</button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分类导航 -->
        <nav class="category-nav">
          <ul class="category-list">
            <!-- 首页链接 -->
            <li class="category-item">
              <router-link to="/" class="category-link" :class="{ active: $route.path === '/' }">
                首页
              </router-link>
            </li>
            <!-- 分类链接 -->
            <li class="category-item" v-for="category in categories" :key="category.id">
              <router-link :to="`/category/${category.id}`" class="category-link">
                {{ category.name }}
              </router-link>
            </li>
          </ul>
        </nav>
    </div>
  </header>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import categoryApi from '../api/categoryApi';
import authApi from '../api/authApi';

export default {
  name: 'NavBar',
  setup() {
    const router = useRouter();
    const route = useRoute();
    const categories = ref([]);
    const showDropdown = ref(false);
    const loggedInStatus = ref(authApi.isLoggedIn());
    const userInfo = ref(authApi.getCurrentUser());
    
    /**
     * 更新登录状态
     */
    const updateLoginStatus = () => {
      loggedInStatus.value = authApi.isLoggedIn();
      userInfo.value = authApi.getCurrentUser();
    };
    
    /**
     * 计算用户是否已登录
     */
    const isLoggedIn = computed(() => {
      return loggedInStatus.value;
    });
    
    /**
     * 计算当前用户信息
     */
    const currentUser = computed(() => {
      return userInfo.value;
    });
    
    /**
     * 获取分类列表
     */
    const fetchCategories = async () => {
      try {
        const response = await categoryApi.getCategories();
        if (response.code === 200) {
          categories.value = response.data;
        } else {
          // 使用模拟数据
          categories.value = [
            { id: 1, name: '动画', icon: '🎬' },
            { id: 2, name: '游戏', icon: '🎮' },
            { id: 3, name: '音乐', icon: '🎵' },
            { id: 4, name: '生活', icon: '🏠' },
            { id: 5, name: '科技', icon: '💻' }
          ];
        }
      } catch (error) {
        console.error('获取分类列表失败:', error);
        // 使用模拟数据
        categories.value = [
          { id: 1, name: '动画', icon: '🎬' },
          { id: 2, name: '游戏', icon: '🎮' },
          { id: 3, name: '音乐', icon: '🎵' },
          { id: 4, name: '生活', icon: '🏠' },
          { id: 5, name: '科技', icon: '💻' }
        ];
      }
    };
    
    /**
     * 处理用户注销
     */
    const handleLogout = () => {
      authApi.logout();
      // 更新登录状态，确保UI刷新
      updateLoginStatus();
      showDropdown.value = false;
      // 如果当前在受保护的页面，跳转到首页
      if (route.meta.requiresAuth) {
        router.push('/');
      }
    };
    
    /**
     * 切换下拉菜单显示状态
     */
    const toggleDropdown = () => {
      showDropdown.value = !showDropdown.value;
    };
    
    // 监听路由变化，关闭下拉菜单并更新登录状态
    watch(() => route.path, () => {
      showDropdown.value = false;
      updateLoginStatus(); // 路由变化时也检查登录状态
    });
    
    // 监听点击外部区域，关闭下拉菜单
    onMounted(() => {
      fetchCategories();
      // 初始加载时检查登录状态
      updateLoginStatus();
      
      const handleClickOutside = (event) => {
        const dropdown = document.querySelector('.user-dropdown');
        if (dropdown && !dropdown.contains(event.target)) {
          showDropdown.value = false;
        }
      };
      
      document.addEventListener('click', handleClickOutside);
      
      return () => {
        document.removeEventListener('click', handleClickOutside);
      };
    });
    
    return {
      categories,
      isLoggedIn,
      currentUser,
      showDropdown,
      handleLogout,
      toggleDropdown
    };
  }
};
</script>

<style scoped>
.header {
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-top {
  display: flex;
  align-items: center;
  padding: 10px 0;
  gap: 20px;
}

.logo {
  font-size: 24px;
  font-weight: bold;
  color: #fb7299;
  flex-shrink: 0;
}

.logo a {
  color: inherit;
  text-decoration: none;
}

.search-box {
  flex: 1;
  display: flex;
  max-width: 500px;
}

.search-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  font-size: 14px;
}

.search-btn {
  padding: 8px 16px;
  background-color: #fb7299;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.user-area {
  margin-left: auto; /* 将用户区域推到最右侧 */
  position: relative;
}

/* 未登录状态样式 */
.login-area {
  display: flex;
  align-items: center;
}

.login-btn {
  padding: 8px 20px;
  background-color: #fb7299;
  color: white;
  border-radius: 4px;
  text-decoration: none;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-btn:hover {
  background-color: #e86388;
}

/* 已登录状态样式 */
.user-info {
  position: relative;
}

.user-dropdown {
  position: relative;
}

.user-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background-color: transparent;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.user-btn:hover {
  background-color: #f5f5f5;
}

.dropdown-arrow {
  font-size: 12px;
  transition: transform 0.3s;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 5px;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-width: 120px;
  z-index: 1001;
}

.dropdown-item {
  display: block;
  width: 100%;
  padding: 10px 16px;
  background: none;
  border: none;
  text-align: left;
  color: #333;
  font-size: 14px;
  cursor: pointer;
  text-decoration: none;
  transition: background-color 0.3s;
}

.dropdown-item:hover {
  background-color: #f5f5f5;
}

.dropdown-item.logout {
  color: #f44336;
}

.dropdown-item.logout:hover {
  background-color: #ffebee;
}

/* 分类导航 */
.category-nav {
  overflow-x: auto;
  white-space: nowrap;
  -webkit-overflow-scrolling: touch;
}

.category-list {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
}

.category-item {
  padding: 10px 15px;
}

.category-link {
  text-decoration: none;
  color: #333;
  font-size: 14px;
  transition: color 0.3s;
}

.category-link:hover,
.category-link.active {
  color: #fb7299;
}
</style>